import axios, { AxiosResponse, AxiosRequestConfig } from 'axios';
import { message, Modal } from 'ant-design-vue';
import {getStore} from '@/utils/store.ts'
import {useRouter} from 'vue-router'
import routes from '../router/router'
import store from '../store/index';
axios.defaults.baseURL = '/api';
axios.defaults.timeout = 300000;

axios.interceptors.request.use((config: AxiosRequestConfig) => {
    const token: string | null = getStore({name:"token"})

    if (token) {
        config.headers['token'] = token;
    }

    return config;
}, (error: any) => Promise.reject(error))



axios.interceptors.response.use((response: AxiosResponse) => {

    if (response.status === 200) {

        const { code, msg } = response.data;

        if (code === 0) {
            return response.data
        }

        //TOKEN失效
        if(code === -2){
            message.warning(msg);
            store.dispatch('USER_LOGOUT');
            routes.push('/')
            return Promise.reject()
        }
        message.warning(msg);
        return Promise.reject()

    }else{
        return Promise.reject()
    }
   
}, (error: Error) => {
    message.error(checkStatus(500));
    return Promise.reject(error)
})


const checkStatus = (status: number): string => {
    const statusMap = new Map();
    statusMap.set(400, '参数有误,请检查');
    statusMap.set(405, '请求方式不正确,请检查');
    statusMap.set(401, '服务器未授权的请求,请联系管理员');
    statusMap.set(403, '服务器拒绝访问,请联系管理员');
    statusMap.set(404, '服务器资源不存在,请联系管理员');
    statusMap.set(500, '服务器出错了,请联系管理员');
    statusMap.set(501, '网络出错,请检查您的网络');
    return statusMap.get(status)
}

export default axios